//
//  GTHomeViewController.swift
//  swiftWEIbo
//
//  Created by mac－gt on 15/11/23.
//  Copyright © 2015年 mac－gt. All rights reserved.
//

import UIKit

import SVPullToRefresh
import SVProgressHUD
// cell类型 枚举
enum GTStatusCellIdentifier: String{
    case NormallCell="NormallCell"
    case FowardCell="FowardCell"
    static  func cellID(status: GTStatus?)-> String{
        return (status?.retweeted_status == nil) ? NormallCell.rawValue : FowardCell.rawValue
    }
}
class GTHomeViewController: GTBasicViewController {
    var statuses: [GTStatus]?{
        didSet{
  
            tableView.reloadData()
        }
    }

    override func viewDidLoad() {
        super.viewDidLoad()
        
        if !GTAcounts.isLogin(){
            return
        }
        setUpNavItems()
        setUp()
//        loadStatus()
        loadNewStatus()
        
    }
    func loadNewStatus(){
        let since_id=statuses?.first?.id ?? 0
        GTStatus.loadStatus(since_id, max_id: 0) { (list, error) -> () in
            self.refreshControl?.endRefreshing()
            if error != nil{
                SVProgressHUD.showErrorWithStatus("加载数据出错")
                print("\(error)")
                return
            }
            let counts=list?.count ?? 0
            if counts==0{
                print("没有加载到数据")
                return
            }
            if since_id > 0{
                print("获取到\(list?.count)条数据")
                self.statuses=list! + self.statuses!
            }else
            {
                self.statuses=list
            }
        }
    }
//        func loadStatus(){
//            GTStatus.loadStatus { (list, error) -> () in
//                if error != nil{
//                    SVProgressHUD.showErrorWithStatus("加载数据出错")
//                    return
//                }
//                self.statuses=list
//                self.refreshControl?.endRefreshing()
//            }
//    }

    func setUp(){
              tableView.separatorStyle=UITableViewCellSeparatorStyle.None
        tableView.estimatedRowHeight = 200
        
        tableView.registerClass(GTretweed_statusCell.self, forCellReuseIdentifier: GTStatusCellIdentifier.FowardCell.rawValue)
        tableView.registerClass(GTStatusNormalCell.self, forCellReuseIdentifier: GTStatusCellIdentifier.NormallCell.rawValue)
          refreshControl=GTRefreshControl()
        refreshControl?.addTarget(self, action: "loadNewStatus", forControlEvents: UIControlEvents.ValueChanged)
        refreshControl?.beginRefreshing()
        refreshControl?.sendActionsForControlEvents(UIControlEvents.ValueChanged)
        tableView.addInfiniteScrollingWithActionHandler { () -> Void in
           self.loadMoreStatus()
        }
        
    }
    func loadMoreStatus(){
        let max_id=statuses?.last?.id ?? 0
        if max_id == 0{
            return
        }
        GTStatus.loadStatus(0, max_id: max_id) { (list, error) -> () in
            self.tableView.infiniteScrollingView.stopAnimating()
            if error != nil{
                SVProgressHUD.showErrorWithStatus("出错了:\(error)")
                 return
            }
           self.statuses=self.statuses! + list!
        }
        
    }
    // 有多少行Cell
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return (statuses?.count) ?? 0
    }
    // cell现实的内容
    override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
          let status=self.statuses?[indexPath.row]
        let cellID=GTStatusCellIdentifier.cellID(status)
         let cell=tableView.dequeueReusableCellWithIdentifier(cellID) as! GTStatusCell
        cell.status=status
        return cell
    }
    // 返回每行cell的高度
    override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
        let status=self.statuses?[indexPath.row]
        if let rowHeight = status?.rowHeight{
         
            return rowHeight
        }
        let cellID=GTStatusCellIdentifier.cellID(status)
        let cell=tableView.dequeueReusableCellWithIdentifier(cellID) as! GTStatusCell
        status?.rowHeight=cell.rowHeight(status)

//        print("\(cell.contentView.subviews)")
      return  (status?.rowHeight)!
    }
    // CELL选中
    override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
        tableView.deselectRowAtIndexPath(indexPath, animated: true)
    }
    //  创建navigationItem
    func setUpNavItems(){
       navigationItem.leftBarButtonItem=UIBarButtonItem(imageNmae: "navigationbar_friendsearch")
        navigationItem.rightBarButtonItem=UIBarButtonItem(imageNmae: "navigationbar_pop")
        let name=GTAcounts.loadAccount()?.name ?? "IOS666"
        let button=GTHomeButton()
        button.setTitle(name, forState: UIControlState.Normal)
        button.setImage(UIImage(named: "navigationbar_arrow_down"), forState: UIControlState.Normal)
        button.setTitleColor(UIColor.blackColor(), forState: UIControlState.Normal)
        button.sizeToFit()
        button.addTarget(self, action: "homeButtonClick:", forControlEvents: UIControlEvents.TouchUpInside)
        
        navigationItem.titleView = button
    }
    //  uibaritem点击
    func homeButtonClick(button:UIButton){
        button.selected = !button.selected
        var transform : CGAffineTransform
        if button.selected{
            transform=CGAffineTransformMakeRotation(CGFloat(M_PI-0.01))
            
        }else{
            transform=CGAffineTransformIdentity
        }
        UIView.animateWithDuration(0.5, animations: { () -> Void in
            button.imageView?.transform=transform
            }) { (_) -> Void in
                
        }
        
    }

}
